﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 销售订单:客户报价单服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class CustomerQuotationService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Customerquotation> _customerQuotationRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public CustomerQuotationService(SqlSugarRepository<Customerquotation> customerQuotationRep, ISqlSugarClient sqlSugarClient)
    {
        _customerQuotationRep = customerQuotationRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询销售订单:客户报价单 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询销售订单:客户报价单")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<CustomerQuotationOutput>> Page(PageCustomerQuotationInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _customerQuotationRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.CustomerName.ToString().Contains(input.Keyword) || u.LineType.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.CustomerName.ToString()), u => u.CustomerName.ToString().Contains(input.CustomerName.ToString().Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.LineType), u => u.LineType.Contains(input.LineType.Trim()))
            .WhereIF(input.CreateTimeRange?.Length == 2, u => u.CreateTime >= input.CreateTimeRange[0] && u.CreateTime <= input.CreateTimeRange[1])
            .LeftJoin<Client>((u, customer) => u.CustomerID == customer.Id)
            .LeftJoin<Client>((u, customer, customerName) => u.CustomerName == customerName.Id)
            .LeftJoin<Quotation>((u, customer, customerName, model) => u.Model == model.Id)
            .Select((u, customer, customerName, model) => new CustomerQuotationOutput
            {
                Id = u.Id,
                CustomerID = u.CustomerID,
                CustomerFkDisplayName = $"{customer.CustomerNumber}",
                CustomerName = u.CustomerName,
                CustomerNameFkDisplayName = $"{customerName.CustomerName}",
                LineType = u.LineType,
                Model = u.Model,
                ModelFkDisplayName = $"{model.ModelName}",
                IsDelete = u.IsDelete,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取销售订单:客户报价单详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取销售订单:客户报价单详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Customerquotation> Detail([FromQuery] QueryByIdCustomerQuotationInput input)
    {
        return await _customerQuotationRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加销售订单:客户报价单 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加销售订单:客户报价单")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddCustomerQuotationInput input)
    {
        var entity = input.Adapt<Customerquotation>();
        return await _customerQuotationRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新销售订单:客户报价单 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新销售订单:客户报价单")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateCustomerQuotationInput input)
    {
        var entity = input.Adapt<Customerquotation>();
        await _customerQuotationRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除销售订单:客户报价单 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除销售订单:客户报价单")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteCustomerQuotationInput input)
    {
        var entity = await _customerQuotationRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _customerQuotationRep.FakeDeleteAsync(entity);   //假删除
        //await _customerQuotationRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除销售订单:客户报价单 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除销售订单:客户报价单")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteCustomerQuotationInput> input)
    {
        var exp = Expressionable.Create<Customerquotation>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _customerQuotationRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _customerQuotationRep.FakeDeleteAsync(list);   //假删除
        //return await _customerQuotationRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataCustomerQuotationInput input)
    {
        var customerIDData = await _customerQuotationRep.Context.Queryable<Client>()
            .InnerJoinIF<Customerquotation>(input.FromPage, (u, r) => u.Id == r.CustomerID)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.CustomerNumber}"
            }).ToListAsync();
        var customerNameData = await _customerQuotationRep.Context.Queryable<Client>()
            .InnerJoinIF<Customerquotation>(input.FromPage, (u, r) => u.Id == r.CustomerName)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.CustomerName}"
            }).ToListAsync();
        var modelData = await _customerQuotationRep.Context.Queryable<Quotation>()
            .InnerJoinIF<Customerquotation>(input.FromPage, (u, r) => u.Id == r.Model)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.ModelName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "customerID", customerIDData },
            { "customerName", customerNameData },
            { "model", modelData },
        };
    }
    
    /// <summary>
    /// 导出销售订单:客户报价单记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出销售订单:客户报价单记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageCustomerQuotationInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportCustomerQuotationOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "销售订单:客户报价单导出记录");
    }
    
    /// <summary>
    /// 下载销售订单:客户报价单数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载销售订单:客户报价单数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportCustomerQuotationOutput>(), "销售订单:客户报价单导入模板", (_, info) =>
        {
            if (nameof(ExportCustomerQuotationOutput.CustomerFkDisplayName) == info.Name) return _customerQuotationRep.Context.Queryable<Client>().Select(u => $"{u.CustomerNumber}").Distinct().ToList();
            if (nameof(ExportCustomerQuotationOutput.CustomerNameFkDisplayName) == info.Name) return _customerQuotationRep.Context.Queryable<Client>().Select(u => $"{u.CustomerName}").Distinct().ToList();
            if (nameof(ExportCustomerQuotationOutput.ModelFkDisplayName) == info.Name) return _customerQuotationRep.Context.Queryable<Quotation>().Select(u => $"{u.ModelName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入销售订单:客户报价单记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入销售订单:客户报价单记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportCustomerQuotationInput, Customerquotation>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 客户编号
                    var customerIDLabelList = pageItems.Where(x => x.CustomerFkDisplayName != null).Select(x => x.CustomerFkDisplayName).Distinct().ToList();
                    if (customerIDLabelList.Any()) {
                        var customerIDLinkMap = _customerQuotationRep.Context.Queryable<Client>().Where(u => customerIDLabelList.Contains($"{u.CustomerNumber}")).ToList().ToDictionary(u => $"{u.CustomerNumber}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.CustomerID = customerIDLinkMap.GetValueOrDefault(e.CustomerFkDisplayName ?? "");
                            if (e.CustomerID == null) e.Error = "客户编号链接失败";
                        });
                    }
                    // 链接 客户名称
                    var customerNameLabelList = pageItems.Where(x => x.CustomerNameFkDisplayName != null).Select(x => x.CustomerNameFkDisplayName).Distinct().ToList();
                    if (customerNameLabelList.Any()) {
                        var customerNameLinkMap = _customerQuotationRep.Context.Queryable<Client>().Where(u => customerNameLabelList.Contains($"{u.CustomerName}")).ToList().ToDictionary(u => $"{u.CustomerName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.CustomerName = customerNameLinkMap.GetValueOrDefault(e.CustomerNameFkDisplayName ?? "");
                            if (e.CustomerName == null) e.Error = "客户名称链接失败";
                        });
                    }
                    // 链接 型号
                    var modelLabelList = pageItems.Where(x => x.ModelFkDisplayName != null).Select(x => x.ModelFkDisplayName).Distinct().ToList();
                    if (modelLabelList.Any()) {
                        var modelLinkMap = _customerQuotationRep.Context.Queryable<Quotation>().Where(u => modelLabelList.Contains($"{u.ModelName}")).ToList().ToDictionary(u => $"{u.ModelName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.Model = modelLinkMap.GetValueOrDefault(e.ModelFkDisplayName ?? "");
                            if (e.Model == null) e.Error = "型号链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<Customerquotation>>();
                    
                    var storageable = _customerQuotationRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.LineType?.Length > 32, "线别长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
